package org.jeecg.modules.charge.controller;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.charge.ChargeInvoice;
import org.jeecg.modules.charge.entity.Cancellaction;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.charge.entity.ChargeInvoiceInhouse;
import org.jeecg.modules.charge.service.IChargeInvoiceInhouseService;
import org.jeecg.modules.charge.service.IChargeInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
* @Description: 票据核销
* @Author: jeecg-boot
* @Date:   2019-08-26
* @Version: V1.0
*/
@Slf4j
@Api(tags="票据核销")
@RestController
@RequestMapping("/b/charge/canlcellation")
public class ChargeInvoiceCancellationController {
    @Autowired
    private IChargeInvoiceInhouseService chargeInvoiceInhouseService;
    @Autowired
    private IChargeInvoiceService chargeInvoiceService;
    /**
     * 分页列表查询
     * @param chargeInvoiceInhouse
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "票据核销-分页列表查询")
    @ApiOperation(value="票据核销-分页列表查询", notes="票据核销-分页列表查询")
    @GetMapping(value = "/lists")
    public Result<IPage<ChargeInvoiceInhouse>> queryPageList(ChargeInvoiceInhouse chargeInvoiceInhouse,
                                                             @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                             HttpServletRequest req) {
        Result<IPage<ChargeInvoiceInhouse>> result = new Result<IPage<ChargeInvoiceInhouse>>();
        List<ChargeInvoiceInhouse> list = new ArrayList<ChargeInvoiceInhouse>();
        try{
            Page<ChargeInvoiceInhouse> page = new Page<ChargeInvoiceInhouse>(pageNo, pageSize);
            if(StringUtils.isNotEmpty(chargeInvoiceInhouse.getGroupNum())){
                list = chargeInvoiceInhouseService.findInvoicePage(page,chargeInvoiceInhouse);
            }
            page.setRecords(list);
            result.setSuccess(true);
            result.setResult(page);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 根据票据ID获取核销票据的集合
     */
    @PostMapping(value = "/getInvoiceCncellation")
    public Result<List<ChargeInvoiceInhouse>> getInvoiceCncellation(@RequestBody ChargeInvoiceInhouse chargeInvoiceInhouse) {
        Result<List<ChargeInvoiceInhouse>>  result = new Result<List<ChargeInvoiceInhouse>>();
        try{
            List<ChargeInvoiceInhouse> houseList = chargeInvoiceInhouseService.findInvoiceList(chargeInvoiceInhouse);
            result.setResult(houseList);
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 票据核销
     */
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Cancellaction cancellaction) {
        Result<String>  result = new Result<String>();
        try{
            Integer results = chargeInvoiceInhouseService.CancellactionHouse(cancellaction);
            if(results > 0){
                result.setResult("票据核销成功！");
                result.setSuccess(true);
            }else{
                result.setResult("票据核销失败！");
                result.setSuccess(false);
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }
    /**
     * 导出excel
     *
     * @param
     * @param response
     */
    @PostMapping(value = "/getInvoiceUrl")
    public void getInvoiceUrl(@RequestBody ChargeInvoice chargeInvoice, HttpServletResponse response) {
        SimpleDateFormat kpsmf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        XSSFWorkbook book = new XSSFWorkbook();
        try {
            List<ChargeInvoice> invoices=chargeInvoiceService.getInvoicesByDmAll(chargeInvoice.getInvoiceDm());
            XSSFSheet sheet = book.createSheet("mySheent");
            String [] vals = {"票据本编号","票据编号","开票日期","开票人","金额","收款日期","收款人","作废日期","作废原因","备注"};
            createExcel(sheet, 0, vals);
            if(invoices != null && invoices.size()>0){
                for(int i=0;i<invoices.size();i++){
                       ChargeInvoice inv= invoices.get(i);
                       String  makeInvoiceDate = "";
                       String zjSkrq = "";
                       String scrapDate = "";
                       if(inv.getMakeInvoiceDate() != null){
                           makeInvoiceDate= kpsmf.format(inv.getMakeInvoiceDate());
                       }
                       if(inv.getZjSkrq() !=null){
                           zjSkrq = kpsmf.format(inv.getZjSkrq());
                       }
                        if(inv.getScrapDate() != null){
                            scrapDate = kpsmf.format(inv.getScrapDate());
                        }
                        String[] vals2 = {inv.getInvoiceDm(),inv.getInvoiceHm(),makeInvoiceDate,
                                inv.getInvoiceMan(),inv.getMoney().toString(),zjSkrq,inv.getPayee(),
                                scrapDate,inv.getScrapDes(),inv.getRemarks()};
                        createExcel(sheet, i+1, vals2);
                }
                book.write(generateResponseExcel("票据详情",response));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    /**
       * @param excelName
       *   要生成的文件名字
       * @return
       * @throws IOException
       */
    private ServletOutputStream generateResponseExcel(String excelName, HttpServletResponse response) throws IOException {
        excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
        return response.getOutputStream();
    }
    private void createExcel(XSSFSheet sheet, int rowNo, String[] vals)  {
        if (vals.length > 0) {
            XSSFRow row = sheet.createRow(rowNo);
            for (int i = 0; i < vals.length; i++) {
                String val = vals[i];
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(val);
            }
        }
    }

}
